package com.moujitx.wecom.controller;

import com.moujitx.wecom.entity.MessageLog;
import com.moujitx.wecom.entity.WecomConfig;
import com.moujitx.wecom.repository.MessageLogRepository;
import com.moujitx.wecom.repository.WecomConfigRepository;
import com.moujitx.wecom.common.Wecom;
import com.moujitx.wecom.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/message")
public class MessageLogController {
    @Autowired
    private MessageLogRepository messageLogRepository;
    
    @Autowired
    private WecomConfigRepository wecomConfigRepository;

    @GetMapping("/history")
    public Result getMessageHistory(
            @RequestParam(required = false) Long destinationId,
            @RequestParam(required = false) String status) {
        try {
            List<MessageLog> logs;
            if (destinationId != null && status != null) {
                logs = messageLogRepository.findByDestinationIdAndStatus(destinationId, status);
            } else if (destinationId != null) {
                logs = messageLogRepository.findByDestinationId(destinationId);
            } else if (status != null) {
                logs = messageLogRepository.findByStatus(status);
            } else {
                logs = messageLogRepository.findAll();
            }
            return Result.ok(logs);
        } catch (Exception e) {
            return Result.serverError("获取发送记录失败: " + e.getMessage());
        }
    }

    @PostMapping("/resend/{id}")
    public Result resendMessage(@PathVariable Long id) {
        try {
            MessageLog messageLog = messageLogRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("消息记录不存在"));

            // 获取对应的配置信息
            Optional<WecomConfig> configOpt = wecomConfigRepository.findById(messageLog.getDestinationId());
            if (!configOpt.isPresent()) {
                return Result.badRequest("配置信息不存在");
            }
            
            WecomConfig config = configOpt.get();
            
            // 获取accessToken
            String accessToken = Wecom.getAccessToken(config.getCorpId(), config.getSecret());
            if (accessToken == null) {
                return Result.badRequest("获取accessToken失败");
            }
            
            switch (messageLog.getMessageType()) {
                case "TEXT":
                    Wecom.sendTextMessage(
                            accessToken,
                            messageLog.getToUser(),
                            messageLog.getContent(),
                            messageLog.getDestinationId().intValue(),
                            config.getId());
                    break;
                case "MARKDOWN":
                    Wecom.sendMarkdownMessage(
                            accessToken,
                            messageLog.getToUser(),
                            messageLog.getContent(),
                            messageLog.getDestinationId().intValue(),
                            config.getId());
                    break;
                case "NEWS":
                    Wecom.sendNewsMessage(
                            accessToken,
                            messageLog.getToUser(),
                            messageLog.getTitle(),
                            messageLog.getContent(),
                            messageLog.getUrl(),
                            messageLog.getPicUrl(),
                            messageLog.getDestinationId().intValue(),
                            config.getId());
                    break;
                case "TEMPLATE_CARD":
                    Wecom.sendTemplateCardMessage(
                            accessToken,
                            messageLog.getToUser(),
                            messageLog.getTitle(),
                            messageLog.getContent(),
                            messageLog.getUrl(),
                            messageLog.getDestinationId().intValue(),
                            config.getId()).toString();
                    break;
                default:
                    throw new RuntimeException("不支持的消息类型");
            }
            
            // 更新消息记录状态
            messageLog.setStatus("SUCCESS");
            messageLogRepository.save(messageLog);
            
            return Result.ok("消息重新发送成功");
        } catch (Exception e) {
            // 更新消息记录状态为失败
            MessageLog messageLog = messageLogRepository.findById(id).orElse(null);
            if (messageLog != null) {
                messageLog.setStatus("FAILED");
                messageLog.setErrorMessage(e.getMessage());
                messageLogRepository.save(messageLog);
            }
            return Result.badRequest("重新发送失败: " + e.getMessage());
        }
    }
}